package com.tengju.payment.infrastructure.repository.transfer;

import com.tengju.payment.domain.model.BusinessType;
import com.tengju.payment.domain.model.TradeStatus;
import com.tengju.payment.domain.model.transfer.*;
import com.tengju.payment.infrastructure.persistence.mybatis.dataobject.TradeRecordDO;
import com.tengju.payment.infrastructure.persistence.mybatis.mapper.TradeRecordMapper;
import com.tengju.payment.infrastructure.repository.convert.RepositoryTransferConvert;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Repository("transferRecordRepository")
public class TransferRecordRepositoryImpl implements TransferRecordRepository {

    @Resource
    private TradeRecordMapper tradeRecordMapper;

    @Override
    public Transfer findByBusinessNo(BusinessNo businessNo) {
        TradeRecordDO tradeRecordDO = tradeRecordMapper.getByBusinessNoType(businessNo.getValue(), BusinessType.TRANSFER.getVal());
        return RepositoryTransferConvert.doToDomain(tradeRecordDO);
    }

    @Override
    public TransferId storeTransfer(TransferForm transferForm) {
        TradeRecordDO tradeRecordDO = RepositoryTransferConvert.domainToDo(transferForm);
        return new TransferId(tradeRecordMapper.insert(tradeRecordDO));
    }

    @Override
    public int updateTransfer(TradeStatus beforeTradeStatus, Transfer transfer) {
        TradeRecordDO tradeRecordDO = RepositoryTransferConvert.domainToDo(transfer);
        return tradeRecordMapper.updateTransfer(beforeTradeStatus.getVal(), tradeRecordDO);
    }

    @Override
    public List<Transfer> findByStatus(TradeStatus tradeStatus) {
        List<TradeRecordDO> tradeRecordDOList = tradeRecordMapper.getByTradeStatus(tradeStatus.getVal());

        return tradeRecordDOList.stream()
                .map(RepositoryTransferConvert::doToDomain)
                .collect(Collectors.toList());
    }

    @Override
    public Transfer findByTradeNo(String tradeNo) {
        TradeRecordDO tradeRecordDO = tradeRecordMapper.getByTradeNo(tradeNo);
        return RepositoryTransferConvert.doToDomain(tradeRecordDO);
    }

}
